package com.cssl.gulimall.order.interceptor;

import com.cssl.common.constant.auth.AuthConstant;
import com.cssl.common.vo.auth.MemberResponseVO;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberResponseVO> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        System.out.println("拦截登录请求" + uri);
        AntPathMatcher antPathMatcher = new AntPathMatcher();// 匹配器
        boolean match = antPathMatcher.match("/order/order/status/**", uri);// 查询订单消息
        boolean match2 = antPathMatcher.match("/order/order/list/**", uri);// 查询订单消息
        if (match || match2) {
            return true;
        }

        //获取会话信息，获取登录用户信息
        HttpSession session = request.getSession();
        MemberResponseVO attribute = (MemberResponseVO)session.getAttribute(AuthConstant.LOGIN_USER);
        if(attribute != null){
            //已登录，放行
            //封装用户信息到threadLocal
            loginUser.set(attribute);
            return true;
        }else {
            //未登录，跳转登录页面
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('请先进行登录，再进行后续操作!');location.href='http://auth.gulimall.com/login.html'</script>");
            out.flush();
            return false;
        }
    }
}
